import {defineStore} from 'pinia';

interface MenuTreeNode {
    icon?: string;
    index: string;
    title: string;
    permiss?: string;
    subs?: MenuTreeNode[];
}

interface webType {
    id: number,
    title: string
}

interface queryType {
    data?: any,
    key: string,
    expirationTime: number
}

export const useMenuStore = defineStore('menu', {
    state: () => {
        return {
            _menuData: <string[]>[],
            _menuList: <MenuTreeNode[]>[],
            _webList: <webType[]>[],
            _webId: '',
            _queryData: <queryType[]>[],
        };
    },
    getters: {
        webId: state => {
            return state._webId;
        },
        webList: state => {
            return state._webList;
        },
        menuList: state => {
            return state._menuList;
        },
        menuData: state => {
            return state._menuData;
        },
        queryData: state => {
            return state._queryData;
        },
        getQueryData: state => {
            const nowTime = Date.now();
            return (key: string) => state._queryData.find((item) => (item.key === key) && (item.expirationTime > nowTime))?.data;
        },
    },
    actions: {
        setWebId(webId: string) {
            this._webId = webId;
        },
        setWebList(webList: webType[]) {
            this._webList = webList;
        },
        setMenuList(menuList: MenuTreeNode[]) {
            this._menuList = menuList;
        },
        setMenuData(menuData: string[]) {
            this._menuData = menuData;
        },
        setQueryData(queryData: {key:string,data?:any}) {
            const index = this._queryData.findIndex(item => item.key === queryData.key);
            const queryDataObj = {
                ...queryData,
                expirationTime: Date.now() + 1000 * 60 * 60 * 24,
            };
            if (index === -1) {
                this._queryData.push(queryDataObj);
            } else {
                this._queryData[index] = queryDataObj;
            }
        },
    },
    persist: true,
});
